<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/2/2 0002
 * Time: 9:54
 */

namespace app\index\controller;


use app\index\model\AuthRule;
use think\facade\Cache;

class Rule extends Base
{
    private $model = null;

    public function initialize()
    {
        parent::initialize();
        $this->model = new AuthRule();
    }

    public function index()
    {
        return $this->fetch();
    }

    public function lst()
    {
        if ($this->request->isAjax()) {
            $list = $this->model->getList();
            $data = getTree2($list);
            return json(['data' => $data]);
        }
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post('data/a');
            $result = $this->validate($data, 'app\index\validate\Rule');
            if ($result !== true) {
                $this->error($result);
            }
            $res = $this->model->add($data);
            if ($res !== false) {
                //删除缓存
                Cache::set('menus', '');
                Cache::set('rule', '');
                $this->success('添加成功');
            }
            $this->error('添加失败');
        }
        $rules = getTree2($this->model->getList());
        $this->assign('rules', $rules);
        return $this->fetch();
    }

    public function edit()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->post('id', 0);
            $data = $this->request->post('data/a');
            $result = $this->validate($data, 'app\index\validate\Rule');
            if ($result !== true) {
                $this->error($result);
            }
            $res = $this->model->edit($id, $data);
            if ($res !== false) {
                //删除缓存
                Cache::set('menus', '');
                Cache::set('rule', '');
                $this->success('编辑成功');
            }
            $this->error('编辑失败');
        }
        $id = $this->request->get('id');
        $rule = $this->model->getOneById($id);
        $rules = getTree2($this->model->getList());

        $this->assign('id', $id);
        $this->assign('rule', $rule);
        $this->assign('rules', $rules);
        return $this->fetch();
    }

    public function del()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->get('id');
            //判断是否有上级
            $rule = $this->model->getChildrenRule($id);
            if ($rule) {
                $this->error('存在下级分类不能删除');
            }
            $res = $this->model->del($id);
            if ($res !== false) {
                //删除缓存
                Cache::set('menus', '');
                Cache::set('rule', '');
                $this->success('删除成功');
            }
            $this->error('删除失败');
        }
        $this->error('请求错误');
    }
}